package com.budwk.app.sqfw.controllers.admin;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.budwk.app.sqfw.annotation.FieldValueAnnotationProcessor;
import com.budwk.app.sqfw.bo.Sqfw_formSummaryForAdminBO;
import com.budwk.app.sqfw.models.Sqfw_formSummary;
import com.budwk.app.sqfw.services.SqfwInfoManageForAdminService;
import com.budwk.app.sqfw.vo.Sqfw_formSummaryForAdminVO;
import com.budwk.app.sys.models.Sys_unit;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysUnitService;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.poiUtils.SqfwInfoDataEasyExcelListener;
import com.budwk.starter.common.openapi.annotation.*;
import com.budwk.starter.common.page.PageUtil;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.common.result.ResultCode;
import com.budwk.starter.log.annotation.SLog;
import com.budwk.starter.security.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.lang.random.R;
import org.nutz.mvc.annotation.*;
import org.nutz.mvc.upload.TempFile;
import org.nutz.mvc.upload.UploadAdaptor;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @program: SqfwInfoManageForAdminController
 * @description: 社区信息管理（后台管理系统）
 * @author: LJT
 * @create: 2023-10-19 10:20
 **/
@IocBean
@At("/platform/sqfw/infoManage")
@ApiDefinition(tag = "社区信息管理（后台管理系统）")
@Slf4j
public class SqfwInfoManageForAdminController {

    private static final String DATE_FLAG = "1";// 时间标识，1-取文档时间，0-取固定时间

    @Inject
    private SqfwInfoManageForAdminService sqfwInfoManageForAdminService;

    @Inject
    private SysUnitService sysUnitService;

    @Inject
    private SysUserService sysUserService;

    /**
     * 后台管理系统任务列表查询（用于后台管理系统）
     * Add by LJT 2023-10-19
     */
    @At("/list")
    @Ok("json")
    @POST
    @ApiOperation(name = "后台管理系统任务列表查询")
    @ApiFormParams(
            value = {
                    @ApiFormParam(name = "pageNo", example = "1", description = "页码", type = "integer"),
                    @ApiFormParam(name = "pageSize", example = "10", description = "页大小", type = "integer"),
                    @ApiFormParam(name = "pageOrderName", example = "createdAt", description = "排序字段"),
                    @ApiFormParam(name = "pageOrderBy", example = "descending", description = "排序方式")
            },
            implementation = Sqfw_formSummaryForAdminVO.class
    )
    @ApiResponses(
            implementation = Sqfw_formSummary.class
    )
    @SLog(tag = "后台管理系统任务列表查询", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> list(@Param("..") Sqfw_formSummaryForAdminVO bean, @Param("pageNo") int pageNo, @Param("pageSize") int pageSize, @Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy) {

        Cnd cnd = Cnd.NEW();
        if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
            cnd.orderBy(pageOrderName, PageUtil.getOrder(pageOrderBy));
        } else {
            cnd.orderBy("fill_date", "desc");
        }
        if (Strings.isNotBlank(bean.getCreateBy())) {
            Cnd cnd1 = Cnd.NEW();
            cnd1.and("username", "like", bean.getCreateBy());
            List<Sys_user> sysUsers = sysUserService.query(cnd1);
            if (sysUsers.size() > 0) {
                bean.setCreateBy(sysUsers.get(0).getId());
            }
        }
        if (Strings.isNotBlank(bean.getCreateBy())) {
            cnd.and("create_by", "=", bean.getCreateBy());
        }
        if (Strings.isNotBlank(bean.getA1())) {
            cnd.and("a1", "like", "%" + bean.getA1() + "%");
        }
        if (Strings.isNotBlank(bean.getA2())) {
            cnd.and("a2", "like", "%" + bean.getA2() + "%");
        }
        if (Strings.isNotBlank(bean.getA3())) {
            cnd.and("a3", "like", "%" + bean.getA3() + "%");
        }
        if (Strings.isNotBlank(bean.getA5())) {
            cnd.and("a5", "like", "%" + bean.getA5() + "%");
        }
        if (Strings.isNotBlank(bean.getA6())) {
            cnd.and("a6", "like", "%" + bean.getA6() + "%");
        }
        if (Strings.isNotBlank(bean.getA7())) {
            cnd.and("a7", "like", "%" + bean.getA7() + "%");
        }
        if (Strings.isNotBlank(bean.getA13())) {
            cnd.and("a13", "like", "%" + bean.getA13() + "%");
        }
        if (Strings.isNotBlank(bean.getA16())) {
            cnd.and("a16", "like", "%" + bean.getA16() + "%");
        }
        if (Strings.isNotBlank(bean.getA17())) {
            cnd.and("a17", "like", "%" + bean.getA17() + "%");
        }
        if (Strings.isNotBlank(bean.getProvince())) {
            cnd.and("province", "like", "%" + bean.getProvince() + "%");
        }
        if (Strings.isNotBlank(bean.getCity())) {
            cnd.and("city", "like", "%" + bean.getCity() + "%");
        }
        if (Strings.isNotBlank(bean.getCounty())) {
            cnd.and("county", "like", "%" + bean.getCounty() + "%");
        }
        if (Strings.isNotBlank(bean.getDistrict())) {
            cnd.and("district", "like", "%" + bean.getDistrict() + "%");
        }
        if (Strings.isNotBlank(bean.getCommunity())) {
            cnd.and("community", "like", "%" + bean.getCommunity() + "%");
        }
        if (Strings.isNotBlank(bean.getCreateUserName())) {
            cnd.and("create_user_name", "like", "%" + bean.getCreateUserName() + "%");
        }
        if (Strings.isNotBlank(bean.getCreateUserPhone())) {
            cnd.and("create_user_phone", "like", "%" + bean.getCreateUserPhone() + "%");
        }
        if (Strings.isNotBlank(bean.getType())) {
            cnd.and("type", "like", "%" + bean.getType() + "%");
        }
        //数据库中存在这种"0001-01-01 00:00:00.000" 历史数据， 需要过滤掉
        cnd.and("fill_date", "=", DateUtil.parse("0001-01-01 00:00:00.000"));

        if (bean.getQueryTime() != null && Strings.isNotBlank(bean.getQueryTime())) {
            String time[] = bean.getQueryTime().split(",");
            cnd.and("fill_date", "between", new Object[]{new Date(Long.valueOf(time[0])), new Date(Long.valueOf(time[1]))});
        }
        Pagination pagination = sqfwInfoManageForAdminService.listPage(pageNo, pageSize, cnd);
        List<Sqfw_formSummary> list = pagination.getList(Sqfw_formSummary.class);
        List<Sqfw_formSummary> resList = new ArrayList<Sqfw_formSummary>();
        for (Sqfw_formSummary summary : list) {
            Sys_user sysUser = sysUserService.fetch(summary.getCreateBy());
            if (null != sysUser && Strings.isNotBlank(sysUser.getUsername())) {
                summary.setCreateBy(sysUser.getUsername());
            }
            resList.add(summary);
        }
        pagination.setList(resList);
        pagination.setPageNo(pageNo);
        pagination.setPageSize(pageSize);
        return Result.success(pagination);
    }


    @At("/update")
    @Ok("json")
    @POST
    @SLog(tag = "修改社区信息", value = "${args[0]}")
    @ApiOperation(name = "修改社区信息")
    @ApiFormParams(
            implementation = Sqfw_formSummary.class
    )
    @ApiResponses
    @SaCheckLogin
    public Result<?> update(@Param("..") Sqfw_formSummary sqfwInfo) {
        int checkNumber = sqfwInfoManageForAdminService.count(Cnd.where("id", "=", sqfwInfo.getId()));
        if (checkNumber <= 0) {
            return Result.error("社区信息不存在！");
        }
        sqfwInfo.setUpdateBy(SecurityUtil.getUserId());
        sqfwInfo.setUpdateDate(new Date());
        sqfwInfo.setUpdateUserName(SecurityUtil.getUserUsername());
        sqfwInfo.setUpdateUserPhone(SecurityUtil.getUserLoginname());
        sqfwInfoManageForAdminService.updateSqfwInfo(sqfwInfo);
        return Result.success();
    }


    /**
     * 导入社区信息
     *
     * @param file
     * @return
     */
    @At("/infoUpload")
    @Ok("json")
    @POST
    @ApiOperation(name = "单个文件上传")
    @SLog(tag = "单个文件上传", value = "${args[0]},${args[1]}")
    @ApiFormParams(
            value = {
                    @ApiFormParam(name = "file", example = "1", description = "文件")
            }
    )
    @AdaptBy(type = UploadAdaptor.class)
    @SaCheckLogin
    public Result<?> upload(@Param("file") TempFile file, @Param("unitId") String unitId) {
        if (Strings.isBlank(unitId)) {
            return Result.error("单位信息不能为空！");
        }
        if (file.getSize() <= 0) {
            return Result.error("文件不能为空！");
        }
        if (!file.getFile().getName().endsWith(".xlsx")) {
            return Result.error("文件格式不正确！");
        }
        // 解析导入文件
        long startTime = System.currentTimeMillis();
        SqfwInfoDataEasyExcelListener<Sqfw_formSummaryForAdminBO> listener = new SqfwInfoDataEasyExcelListener<>();
        try {
            EasyExcel.read(file.getInputStream(), Sqfw_formSummaryForAdminBO.class, listener).sheet(0).doReadSync();
            List<Sqfw_formSummaryForAdminBO> data = listener.getData();
            String userId = SecurityUtil.getUserId();
            List<Sqfw_formSummary> finalData = new ArrayList<Sqfw_formSummary>();
            for (Sqfw_formSummaryForAdminBO summaryBO : data) {
                FieldValueAnnotationProcessor.process(summaryBO);
                Sqfw_formSummary summaryFinal = new Sqfw_formSummary();
                BeanUtil.copyProperties(summaryBO, summaryFinal);
                summaryFinal.setId(R.UU32());
                summaryFinal.setCreateDate(DateUtil.parse("0001-01-01 00:00:00.000"));
                if (DATE_FLAG.equals(summaryBO.getDateFlag())) {
                    summaryFinal.setFillDate(DateUtil.parse(summaryBO.getFillDate()));
                } else {
                    summaryFinal.setFillDate(DateUtil.parse("0001-01-01 00:00:00.000"));
                }
                summaryFinal.setCreateBy(userId);
                summaryFinal.setUnitId(unitId);
                finalData.add(summaryFinal);
            }
            long parseTime = System.currentTimeMillis();
            log.info("解析excel文件时间:{}ms", (parseTime - startTime));
            sqfwInfoManageForAdminService.InsertSqfwInfo(finalData);
            long insertTime = System.currentTimeMillis();
            log.info("数据入表时间:{}ms", (insertTime - parseTime));
            int importNum = listener.getData().size();
            if (0 < importNum) {
                return Result.success("成功导入数据 " + importNum + " 条");
            } else {
                return Result.error("无有效数据导入");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            listener.clear();
        }
        return Result.error("无有效数据导入");
    }


    /**
     * 后台管理系统根据行姓名查unitId（用于后台管理系统）
     * Add by LJT 2023-10-19
     */
    @At("/queryUnit")
    @Ok("json")
    @POST
    @ApiOperation(name = "后台管理系统查询单位列表查询")
    @ApiFormParams(
            implementation = Sys_unit.class
    )
    @ApiResponses(
            implementation = Sys_unit.class
    )
    @SLog(tag = "后台管理系统查询单位列表查询", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> queryUnit(@Param("..") Sys_unit bean) {
        Cnd cnd = Cnd.NEW();
        if (Strings.isNotBlank(bean.getName())) {
            cnd.and("name", "like", "%" + bean.getName() + "%");
        }
        List<Sys_unit> unitInfoList = sysUnitService.query(cnd);
        return Result.success(unitInfoList);
    }


    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @At("/batchDelete")
    @Ok("json")
    @POST
    @ApiOperation(name = "批量删除表数据")
    @SLog(tag = "批量删除表数据", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> delete(@Param("ids") List<String> ids) {
        sqfwInfoManageForAdminService.delete(ids);
        return Result.success();
    }
}
